﻿using King.Box.AdminWeb.Logic;
using King.Box.Utils.Global;
using King.Box.Utils.Utils;
using Newtonsoft.Json;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Net.Http;
using System.Net.Http.Formatting;
using System.Net.Http.Headers;
using System.Text;
using System.Threading.Tasks;

namespace King.Box.AdminWeb.Utils
{
    public class ApiClientUtil
    {
        public static T Get<T>(string url)
        {
            return Get<T>(url, string.Empty);
        }

        public static T Get<T>(string url, string content, string contentType = "application/json")
        {
            if (!string.IsNullOrEmpty(url))
                url = string.Concat(GlobalConfig.ApiAddress, url);
            if (!string.IsNullOrEmpty(content))
                url = string.Concat(url, "?", content);

            var response = HttpClientUtil.Get(url, contentType, "application/json", AuthorizationApiService.AuthorizationHeader);
            return JsonConvert.DeserializeObject<T>(response);
        }

        public static T Get<T>(string url, object content)
        {
            var tempContent = string.Empty;
            if (content != null)
                tempContent = JsonConvert.SerializeObject(content);

            return Get<T>(url, tempContent);
        }

        public static T Get<T>(string url, Dictionary<string, object> content)
        {
            var tempContent = string.Empty;
            if (content != null)
                tempContent = Util.ParseDictionaryToQueryString(content);

            return Get<T>(url, tempContent, "application/x-www-form-urlencoded");
        }

        public static T Post<T>(string url, string content, string contentType = "application/json")
        {
            if (!string.IsNullOrEmpty(url))
                url = string.Concat(GlobalConfig.ApiAddress, url);

            var response = HttpClientUtil.Post(url, content, contentType, "application/json", AuthorizationApiService.AuthorizationHeader);
            return JsonConvert.DeserializeObject<T>(response);
        }

        public static T Post<T>(string url, object content)
        {
            var tempContent = string.Empty;
            if (content != null)
                tempContent = JsonConvert.SerializeObject(content);

            return Post<T>(url, tempContent);
        }

        public static T Post<T>(string url)
        {
            return Post<T>(url, string.Empty);
        }

        public static T Post<T>(string url, Dictionary<string, object> content)
        {
            var tempContent = string.Empty;
            if (content != null)
                tempContent = Util.ParseDictionaryToQueryString(content);

            return Post<T>(url, tempContent, "application/x-www-form-urlencoded");
        }
    }
}
